package org.dromara.common.satoken.handler

import cn.dev33.satoken.exception.NotLoginException
import cn.dev33.satoken.exception.NotPermissionException
import cn.dev33.satoken.exception.NotRoleException
import cn.hutool.http.HttpStatus
import io.github.oshai.kotlinlogging.KotlinLogging
import jakarta.servlet.http.HttpServletRequest
import org.dromara.common.core.domain.R
import org.dromara.common.core.domain.R.Companion.fail
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice

/**
 * SaToken异常处理器
 *
 * @author LikeYouDo
 * @date 2025/7/16
 */
@RestControllerAdvice
class SaTokenExceptionHandler {

    companion object {
        private val log = KotlinLogging.logger { }
    }

    /**
     * 权限码异常
     */
    @ExceptionHandler(NotPermissionException::class)
    fun handleNotPermissionException(e: NotPermissionException, request: HttpServletRequest): R<Void?> {
        val requestURI = request.requestURI
        log.error { "${"请求地址'{}',权限码校验失败'{}'"} $requestURI ${e.message}" }
        return fail<Void>(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权")
    }

    /**
     * 角色权限异常
     */
    @ExceptionHandler(NotRoleException::class)
    fun handleNotRoleException(e: NotRoleException, request: HttpServletRequest): R<Void?> {
        val requestURI = request.requestURI
        log.error { "${"请求地址'{}',角色权限校验失败'{}'"} $requestURI ${e.message}" }
        return fail<Void>(HttpStatus.HTTP_FORBIDDEN, "没有访问权限，请联系管理员授权")
    }

    /**
     * 认证失败
     */
    @ExceptionHandler(NotLoginException::class)
    fun handleNotLoginException(e: NotLoginException, request: HttpServletRequest): R<Void?> {
        val requestURI = request.requestURI
        log.error { "${"请求地址'{}',认证失败'{}',无法访问系统资源"} $requestURI ${e.message}" }
        return fail<Void>(HttpStatus.HTTP_UNAUTHORIZED, "认证失败，无法访问系统资源")
    }
}
